package date;

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ThreadLocalDemo {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");

    private static ThreadLocal<SimpleDateFormat> threadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyymmdd"));
    @Test
    public  void safe() {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    threadLocal.get().parse("20211203");
                    threadLocal.remove();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
    @Test
    public  void unsafe() {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    sdf.parse("20211203");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
